//
//  GoodsMessageViewController.m
//  MyProject
//
//  Created by dllo on 15/10/30.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "GoodsMessageViewController.h"
#import "GoodsWithMessage.h"
#import "GoodsMarkTableViewCell.h"
#import "GoodsWithMessageTableViewCell.h"
#import "HandleData.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "GoodsSubject.h"
#import "Goods.h"
#import "GoodsWithMessage.h"
#import "MBProgressHUD.h"
#import "GoodsMessageLastViewController.h"


@interface GoodsMessageViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    MBProgressHUD *hud;
}
@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) GoodsSubject *good;
@property (nonatomic ,strong) NSMutableArray *topArr;


@end

@implementation GoodsMessageViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        self.tableView.backgroundColor = [UIColor grayColor];
    }
    else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    self.tabBarController.tabBar.hidden = NO;
    [self saveColor];
    [self.tableView reloadData];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
   // [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    
    
    [self createTableView];
    [self handleDataToTableView];
    [self handleData];
    hud = [[MBProgressHUD alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:hud];
    [hud show:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.detailsLabelText = @"加载中...";
    NSLog(@"======%@",self.good.nameId);
    
}





//创建tableView

- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    [self.tableView registerClass:[GoodsMarkTableViewCell class] forCellReuseIdentifier:@"top"];
    [self.tableView registerClass:[GoodsWithMessageTableViewCell class] forCellReuseIdentifier:@"message"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.topArr.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        GoodsMarkTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"top"];
        [cell.topImageView sd_setImageWithURL:[NSURL URLWithString:self.good.pic1] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
        [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:self.good.avatar1] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
        cell.nameLable.text = self.good.username;
        cell.timeLable.text = self.good.datestr;
        cell.messageLable.text = self.good.descrip;
        
        cell.backgroundColor  = [UIColor clearColor];
        
        if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
            cell.nameLable.textColor = [UIColor whiteColor];
            cell.timeLable.textColor = [UIColor whiteColor];
            cell.messageLable.textColor = [UIColor whiteColor];
        }
        else {
            cell.nameLable.textColor = [UIColor blackColor];
            cell.timeLable.textColor = [UIColor blackColor];
            cell.messageLable.textColor = [UIColor blackColor];
        }
        return cell;
    }
    else{
        GoodsWithMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"message"];
        if (self.topArr.count != 0) {
            GoodsWithMessage *message = [self.topArr objectAtIndex:(indexPath.row - 1)];
            [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:message.avatar1] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
            cell.nameLable.text = message.username;
            cell.timeLable.text = message.datestr;
            [cell.bigImageView sd_setImageWithURL:[NSURL URLWithString:message.url] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
            cell.messageLable.numberOfLines = 0;
            cell.messageLable.text = message.content;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.backgroundColor  = [UIColor clearColor];
            
            if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
                cell.nameLable.textColor = [UIColor whiteColor];
                cell.timeLable.textColor = [UIColor whiteColor];
                cell.messageLable.textColor = [UIColor whiteColor];
            }
            else {
                cell.nameLable.textColor = [UIColor blackColor];
                cell.timeLable.textColor = [UIColor blackColor];
                cell.messageLable.textColor = [UIColor blackColor];
            }
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        CGRect rect = [self.good.descrip boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
        
        return [UIScreen mainScreen].bounds.size.height*2/5 + 51 + rect.size.height;
    }
    else{
        if (self.topArr.count != 0) {
            GoodsWithMessage *message = [self.topArr objectAtIndex:(indexPath.row-1)];
            CGRect rect = [message.content boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
            return 51 + [UIScreen mainScreen].bounds.size.width + rect.size.height+10;
        }
        else{
            return 0;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row > 0) {
        if (self.topArr.count != 0) {
            
            GoodsMessageLastViewController *goods = [[GoodsMessageLastViewController alloc]init];
            [self.navigationController pushViewController:goods animated:YES];
            goods.good = [self.topArr objectAtIndex:(indexPath.row - 1)];
        }
    }
}


//处理数据

- (void)handleData
{
    NSString *str = [NSString stringWithFormat:@"http://open4.bantangapp.com/community/subject/info?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.1&os_versions=4.4.2&screensize=1080&v=6&subject_id=%@",self.Id];
    [HandleData handleDataWithUrl:str completion:^(id data) {
      NSDictionary *dic = [[data objectForKey:@"data"] objectForKey:@"subject"];
        GoodsSubject *good = [[GoodsSubject alloc]init];
        [good setValuesForKeysWithDictionary:dic];
        self.good = good;
//        self.topArr = [NSMutableArray array];
//        NSArray *arr = [[[[data objectForKey:@"data"] objectForKey:@"subject"] objectForKey:@"dynamic"] objectForKey:@"rank_list"];
//        NSMutableArray *array  = [NSMutableArray array];
//        for (NSDictionary *dic1 in arr) {
//            GoodsWithMessage *good = [[GoodsWithMessage alloc]init];
//            [good setValuesForKeysWithDictionary:dic1];
//            [array addObject:good];
//        }
//        [self.topArr addObjectsFromArray:array];
//        [self.tableView reloadData];
    }];
    [self refresh];
 }

- (void)refresh
{
    self.tableView.header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        
        NSString *str = [NSString stringWithFormat:@"http://open4.bantangapp.com/topic/list?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.3&os_versions=4.4.2&screensize=1080&v=6&oauth_token=08e623418ebf12fe438fb9eed5d176da&screensize=1080&page=0&pagesize=100&ids=%@",self.Id];
        [HandleData handleDataWithUrl:str completion:^(id data) {
            NSDictionary *dic = [[data objectForKey:@"data"] objectForKey:@"subject"];
            GoodsSubject *good = [[GoodsSubject alloc]init];
            [good setValuesForKeysWithDictionary:dic];
            self.good = good;
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }];
    }];
}

- (void)handleDataToTableView
{
    NSString *str = [NSString stringWithFormat:@"http://open4.bantangapp.com/community/subject/listPost?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.3&os_versions=4.4.2&screensize=1080&v=6&page=0&pagesize=10&subject_id=%@&type_id=1",self.Id];
    
    [HandleData handleDataWithUrl:str completion:^(id data) {
            self.topArr = [NSMutableArray array];
        NSArray *arr = [[data objectForKey:@"data"] objectForKey:@"list"];
        NSMutableArray *array  = [NSMutableArray array];
        for (NSDictionary *dic1 in arr) {
            GoodsWithMessage *good = [[GoodsWithMessage alloc]init];
            [good setValuesForKeysWithDictionary:dic1];
            [array addObject:good];
        }
        [self.topArr addObjectsFromArray:array];
        if (self.topArr.count != 0) {
            hud.hidden = YES;
        }
        [self.tableView reloadData];
    }];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
